<!--发表文章-->
<template>
  <div>
    <f-header></f-header>
    <div class="m-container">
      <div class="m-content">
        <el-form
          ref="editForm"
          status-icon
          :model="editForm"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item> </el-form-item>

          <el-form-item label="标题" prop="title">
            <el-input v-model="editForm.title"></el-input>
          </el-form-item>
          <!--  <el-form-item label="摘要" prop="description">
          <el-input type="textarea" v-model="editForm.description"></el-input>
        </el-form-item>-->
          <el-form-item label="版块" prop="forum">
            <el-select
              v-model="select"
              @change="selectCategory"
              placeholder="请选择"
            >
              <el-option
                v-for="item in optionsList"
                :key="item.id"
                :label="item.sectionName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <mavon-editor
              v-model="editForm.content"
              ref="md"
              :ishljs="true"
              @change="change"
              :toolbars="markdownOption"
              @imgAdd="$imgAdd"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="editPost()">编辑提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <!-- 返回顶部 -->
    <el-backtop bottom="350"></el-backtop>
  </div>
</template>
<script>
export default {
  name: "postEdit",
  data() {
    return {
      select: "",
      editForm: {
        id: null,
        title: "",
        content: "",
        description: "",
        userId: this.$store.state.userInfo.id,
        categoryId: null,
      },
      markdownOption: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        strikethrough: true, // 中划线
        mark: true, // 标记
        superscript: true, // 上角标
        subscript: true, // 下角标
        quote: true, // 引用
        ol: true, // 有序列表
        ul: true, // 无序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        code: true, // code
        table: true, // 表格
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        htmlcode: true, // 展示html源码
        help: true, // 帮助
        /* 1.3.5 */
        undo: true, // 上一步
        redo: true, // 下一步
        trash: true, // 清空
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true, // 导航目录
        /* 2.1.8 */
        alignleft: true, // 左对齐
        aligncenter: true, // 居中
        alignright: true, // 右对齐
        /* 2.2.1 */
        subfield: true, // 单双栏模式
        preview: true, // 预览
      },

      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 3,
            max: 50,
            message: "长度在 3 到 50 个字符",
            trigger: "blur",
          },
        ],

        description: [
          { required: true, message: "请输入摘要", trigger: "blur" },
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" },
        ],
      },
      optionsList: [],
    };
  },
  created() {
    //获取传进来的postId并初始化文章
    this.postsView();
    //获取所有版块名称信息，赋值给optionsList
    this.plate();
  },
  methods: {
    //获取文章内容
    postsView() {
      const postsId = this.$route.params.postsId;
      const _this = this;
      this.$axios
        .post("/forum/posts/getPostById?postsId=" + postsId)
        .then((res) => {
          console.log(res);
          if (res.data.code === 200) {
            _this.editForm.id = res.data.data.id;
            _this.editForm.title = res.data.data.title;
            _this.editForm.content = res.data.data.content;
            _this.select = res.data.data.description;
            _this.editForm.description = res.data.data.description;
            _this.editForm.categoryId = res.data.data.categoryId;
            _this.editForm.userId = res.data.data.userId;
          }
        });
    },
    //获取所有版块名称
    plate() {
      var _this = this;
      _this.$axios.post("/forum/category/list?curr=" + 1).then((res) => {
        console.log(res);
        _this.optionsList = res.data.data.records;
        console.log(_this.optionsList);
      });
    },

    //根据下拉框的值获取版块id个板块名
    selectCategory(value) {
      console.log(value);
      const category = this.optionsList.find((item) => {
        return item.id === value;
      });
      console.log(category.sectionName);
      this.editForm.categoryId = value;
      this.editForm.description = category.sectionName;
      // alert(category);
    },

    //markdown数据改变
    change(value, render) {
      this.editForm.contentMd = value;
      this.editForm.contentHtml = render;
    },
    //添加图片
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      const _this = this;
      let multipartFile = new FormData();
      multipartFile.append("multipartFile", $file);
      // console.log(multipartFile);
      // console.log($file);
      this.$axios({
        url: "/forum/posts/uploadPic?userId=" + this.editForm.userId,
        method: "post",
        data: multipartFile,
        headers: { "Content-Type": "multipart/form-data" },
      })
        .then((res) => {
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          /**
           * $vm 指为mavonEditor实例，可以通过如下两种方式获取
           * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
           * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
           */
          //  $vm.$img2Url(pos, url);
          console.log("上传图片了哦");
          console.log(res);
          console.log(res.data.data);
          this.$refs.md.$img2Url(pos, res.data.data);
        })
        .catch(() => {
          this.$message.error("上传图片失败！");
        });
    },
    //删除图片
    $imgDel(pos) {
      // delete this.imgFile[pos];
    },

    //编辑文章
    editPost() {
      const _this = this;

      // console.log(this.editForm);
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          //获取markdown
          // let markdown = this.$refs.md.d_value;
          //获取编译后的HTML
          // let mdhtml = this.$refs.md.d_render;
          //修改markdownS
          // this.$refs.md.d_value = ">hello world";
          if (this.editForm.categoryId === null) {
            this.$message({
              message: "发表失败，请选择板块！",
              type: "error",
            });
            return;
          }
          const posts = this.editForm;
          console.log("编辑:");
          console.log(posts);
          this.$axios({
            url: "/forum/posts/updatePostById",
            method: "post",
            data: posts,
          }).then((res) => {
            console.log(res);
            if (res.data.code === 200) {
              _this.$alert("编辑成功", "提示", {
                confirmButtonText: "确定",
                callback: (action) => {
                  _this.$router.push("/detail/" + this.$route.params.postsId);
                },
              });
            } else {
              this.$message({
                message: "发表失败，请重新尝试",
                type: "error",
              });
            }
          });
        } else {
          this.$message({
            message: "请准确填写信息",
            type: "error",
          });

          return false;
        }
      });
    },
  },
};
</script>
<style lang="less">
.m-container {
  width: 80%;
  margin: 0 auto;
}
h1 {
  text-align: left;
}
.el-select {
  float: left;
}
</style>
